/**
 * 
 */
package cn.com.xf.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.Constants;
import cn.com.xf.common.StringUtil;
import cn.com.xf.domain.TblCheckDevice;
import cn.com.xf.domain.TblCheckLeave;
import cn.com.xf.domain.TblOaAuthPermission;
import cn.com.xf.domain.TblOaAuthRole;
import cn.com.xf.domain.TsUser;
import cn.com.xf.service.SettingService;
import cn.com.xf.utils.encode.EncrypTool;
import cn.com.xf.web.PageModel;
import cn.com.xf.web.XFMappingJacksonJsonView;
import cn.com.xf.web.form.LeaveForm;
import cn.com.xf.web.form.SettingForm;

/**
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/setting")
public class SettingController extends AbstractBaseController {
	@Autowired
	private SettingService settingService;

	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		form.setTab(Constants.TAB_SETTING);
		ModelAndView mv = new ModelAndView("/setting/index", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	@RequestMapping(value = "/role/list")
	public ModelAndView soft_list(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/role_list", Constants.FORM_COMMAND_KEY, form);
		// List<AuthRole> list = settingService.selectRoleList();
		// mv.addObject("list", list);
		return mv;
	}

	@RequestMapping(value = "/role/listPermission")
	public ModelAndView listPermission(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/rolePremission_list", Constants.FORM_COMMAND_KEY, form);
		// 参数
		// Long.valueOf(EncrypTool.dencode(roleIdStr)); // 查询
		// List<AuthPermission>
		// list = settingService.selectRolePermissonListByRoleId(roleId);
		// mv.addObject("list", list);
		return mv;
	}

	/**
	 * 用户列表
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/listUser")
	public ModelAndView listUser(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/user_list", Constants.FORM_COMMAND_KEY, form);
		// 1.模糊搜索关键字
		String userId = StringUtil.StringFilter(form.getUserId());
		String userName = StringUtil.StringFilter(form.getUserName());
		String siteId = StringUtil.StringFilter(form.getSiteId());
		String deptId = StringUtil.StringFilter(form.getDeptId());
		String enabled = StringUtil.StringFilter(form.getEnabled());

		String createDateBegin = form.getCreateDateBegin();
		String createDateEnd = form.getCreateDateEnd();

		form.setUserId(userId);
		form.setUserName(userName);
		form.setSiteId(siteId);
		form.setDeptId(deptId);
		form.setEnabled(enabled);

		form.setCreateDateBegin(createDateBegin);
		form.setCreateDateEnd(createDateEnd);

		// 2.总记录数
		int count = settingService.selectUserListCount(userId, userName, siteId, deptId, enabled, createDateBegin,
				createDateEnd);
		if (count == 0) {
			return mv;
		}

		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		// 4.排序规则
		String orderByField = "CREATEDATE";
		String orderByMode = "DESC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("createDate".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "CREATEDATE";
			}
			if ("userId".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "USERID";
			}
			if ("userName".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "USERNAME";
			}
			if ("siteId".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "SITEID";
			}
			if ("enabled".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "ENABLED";
			}

			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}

		// 5.查询
		List<TsUser> userList = settingService.selectUserList(orderByField, orderByMode, userId, userName, siteId,
				deptId, enabled, createDateBegin, createDateEnd, begin, pageSize);
		mv.addObject("userList", userList);
		return mv;
	}

	/**
	 * 添加OA用户
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addUser")
	public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/user_add", Constants.FORM_COMMAND_KEY, form);
		List<TblOaAuthRole> roleList = settingService.selectRoleList();
		mv.addObject("roleList", roleList);
		return mv;
	}

	/**
	 * 添加 执行
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doAddUser")
	public ModelAndView doAddUser(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/user_add_result", Constants.FORM_COMMAND_KEY, form);
		if (StringUtils.isNotBlank(form.getUserId()) && StringUtils.isNotBlank(form.getUserName())
				&& StringUtils.isNotBlank(form.getRoles())) {
			// 1.检测重复
			TsUser existUser = settingService.selectByUserId(form.getUserId().trim());
			if (null == existUser) {
				settingService.insertUser(form);
				mv.addObject("status", "SUCCESS");
				return mv;
			}
			mv.addObject("msg", "用户ID已存在,请勿重复添加");
			mv.addObject("status", "FAILD");
			return mv;
		}

		mv.addObject("msg", "请填写字段完整");
		mv.addObject("status", "FAILD");
		return mv;
	}

	/**
	 * 删除用户
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doDeleteUser")
	public ModelAndView doDeleteUser(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		String userId = form.getUserId();
		int result = settingService.deleteUserByUserId(userId);
		// settingService.insertUser(form);
		Map map = new HashMap<String, String>();
		if (result == -1) {
			map.put("status", "FAILD");
		} else if (result == 0) {
			map.put("status", "SUCCESS");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}

	/**
	 * 编辑页面
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/editUser")
	public ModelAndView editUser(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		String userId = form.getUserId();
		ModelAndView mv = new ModelAndView("/setting/user_edit", Constants.FORM_COMMAND_KEY, form);
		TsUser user = settingService.selectUserWithRoleByUserId(userId);
		List<TblOaAuthRole> roleList = settingService.selectRoleList();
		mv.addObject("roleList", roleList);
		mv.addObject("user", user);
		return mv;
	}

	/**
	 * 提交编辑用户
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doEditUser")
	public ModelAndView doEditUser(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/user_edit_result", Constants.FORM_COMMAND_KEY, form);
		if (StringUtils.isNotBlank(form.getUserId()) && StringUtils.isNotBlank(form.getRoles())) {
			// 1.检测重复
			TsUser existUser = settingService.selectByUserId(form.getUserId().trim());
			if (null != existUser) {
				settingService.updateUser(form);
				mv.addObject("status", "SUCCESS");
				return mv;
			}
			mv.addObject("msg", "该用户不存在");
			mv.addObject("status", "FAILD");
			return mv;
		}

		mv.addObject("msg", "提交数据有误，请不要留空值，请勿改动页面");
		mv.addObject("status", "FAILD");
		return mv;
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addRole")
	public ModelAndView addRole(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/role_add", Constants.FORM_COMMAND_KEY, form);
		List<TblOaAuthPermission> permissionlist = settingService.selectAllPremission();
		mv.addObject("rolepermissionlistList", permissionlist);
		return mv;
	}

	/**
	 * 添加角色执行
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doAddRole")
	public ModelAndView doAddRole(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/role_add_result", Constants.FORM_COMMAND_KEY, form);
		if (StringUtils.isNotBlank(form.getRoleDesc()) && StringUtils.isNotBlank(form.getPermissioins())) {
			// 1.检测重复
			TblOaAuthRole existRole = settingService.selectRoleByDesc(form.getRoleDesc());
			if (null == existRole) {
				if (form.getRoleDesc().contains(",")) {
					mv.addObject("msg", "角色名称包含非法字符");
					mv.addObject("status", "FAILD");
					return mv;
				}
				settingService.insertRole(form);
				mv.addObject("status", "SUCCESS");
				return mv;
			}
			mv.addObject("msg", "该角色名称已存在,请勿重复添加");
			mv.addObject("status", "FAILD");
			return mv;
		}

		mv.addObject("msg", "请填写字段完整");
		mv.addObject("status", "FAILD");
		return mv;
	}

	/**
	 * 角色列表
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/listRole")
	public ModelAndView listRole(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/role_list", Constants.FORM_COMMAND_KEY, form);
		// 1.模糊搜索关键字
		String roleDesc = StringUtil.StringFilter(form.getRoleDesc());
		form.setRoleDesc(roleDesc);

		// 2.总记录数
		int count = settingService.selectRoleListCount(roleDesc);
		if (count == 0) {
			return mv;
		}

		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		// 4.排序规则
		String orderByField = "ROLE_DESC";
		String orderByMode = "ASC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("roleDesc".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "ROLE_DESC";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}

		// 5.查询
		List<TblOaAuthRole> roleList = settingService.selectRoleList(orderByField, orderByMode, roleDesc, begin,
				pageSize);
		mv.addObject("roleList", roleList);
		return mv;
	}

	/**
	 * 删除角色
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doDeleteRole")
	public ModelAndView doDeleteRole(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		String roleId = form.getRoleId();
		if (StringUtils.isNotBlank(roleId)) {
			roleId = EncrypTool.dencode(roleId);
		}
		int result = settingService.deleteRoleByRoleId(roleId);
		Map map = new HashMap<String, String>();
		if (result == -1) {
			map.put("status", "FAILD");
		} else if (result == 0) {
			map.put("status", "SUCCESS");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}

	/**
	 * 编辑角色
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/editRole")
	public ModelAndView editRole(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		String roleId = form.getRoleId();
		if (StringUtils.isNotBlank(roleId)) {
			roleId = EncrypTool.dencode(roleId);
		} else {
			return null;
		}
		ModelAndView mv = new ModelAndView("/setting/role_edit", Constants.FORM_COMMAND_KEY, form);
		TblOaAuthRole role = settingService.selectRoleByRoleId(roleId);
		List<TblOaAuthPermission> permissionlist = settingService.selectAllPremission();
		mv.addObject("permissionlist", permissionlist);
		mv.addObject("role", role);
		return mv;
	}

	/**
	 * 提交编辑角色
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doEditRole")
	public ModelAndView doEditRole(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/setting/role_edit_result", Constants.FORM_COMMAND_KEY, form);
		if (StringUtils.isNotBlank(form.getRoleId()) && StringUtils.isNotBlank(form.getRoleDesc())
				&& StringUtils.isNotBlank(form.getPermissioins())) {
			String realRoleId = EncrypTool.dencode(form.getRoleId());
			// 1.检测重复
			TblOaAuthRole existRole = settingService.selectRoleByRoleId(realRoleId);
			if (null != existRole) {
				settingService.updateRole(realRoleId, form.getRoleDesc(), form.getPermissioins());
				mv.addObject("status", "SUCCESS");
				return mv;
			}
			mv.addObject("msg", "该角色不存在");
			mv.addObject("status", "FAILD");
			return mv;
		}

		mv.addObject("msg", "提交数据有误，请不要留空值，请勿改动页面");
		mv.addObject("status", "FAILD");
		return mv;
	}

	
	@RequestMapping(value = "/addDevice")
	public ModelAndView addDevice(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/device_add", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}
	
	@RequestMapping(value = "/doAddDevice")
	public ModelAndView doAddDevice(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/device_add_result", Constants.FORM_COMMAND_KEY, form);
		if (StringUtils.isNotBlank(form.getDeviceName()) && StringUtils.isNotBlank(form.getSn()) && StringUtils.isNotBlank(form.getSiteId())) {
			String[] siteids = form.getSiteId().split(",");
			for (String siteid: siteids) {
				TblCheckDevice device = new TblCheckDevice();
				device.setSn(form.getSn());
				device.setSiteid(siteid);
				device.setName(form.getDeviceName());
				device.setAddtime(new Date());
				settingService.insertDevice(device);
			}
			mv.addObject("status", "SUCCESS");
			return mv;
		}
		mv.addObject("msg", "请填写字段完整");
		mv.addObject("status", "FAILD");
		return mv;
	}
	
	@RequestMapping("/deviceList")
	public ModelAndView deviceList(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/device_list", Constants.FORM_COMMAND_KEY, form);
		String siteid = StringUtil.StringFilter(form.getSiteId());
		String sn = StringUtil.StringFilter(form.getSn());
		String status = StringUtil.StringFilter(form.getStatus());
		form.setSiteId(siteid);
		form.setSn(sn);
		form.setStatus(status);
		
		if (status.equals("1")) {
			status = "离线";
		} else if (status.equals("0")) {
			status = "在线";
		} else {
			status = "";
		}
		
		int count = settingService.selectDeviceCount(siteid, sn, status);
		if (count == 0)
			return mv;

		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		List<TblCheckDevice> list = settingService.selectDevices(begin, pageSize, siteid, sn, status);
		mv.addObject("list", list);
		return mv;
	}
	
	@RequestMapping("/deleteDevice")
	@ResponseBody
	public Map<String, Object> deleteDevice(HttpServletRequest request, HttpServletResponse response, SettingForm form)
			throws Exception {
		String idStr = form.getId();
		String realId = "";
		if (StringUtils.isNotBlank(idStr)) {
			realId = EncrypTool.dencode(idStr);
		}
		int result = settingService.deleteDevice(new Long(realId));
		Map<String, Object> map = new HashMap<String, Object>();
		if (result > 0) {
			map.put("status", "FAILD");
		} else {
			map.put("status", "SUCCESS");
		}
		return map;
	}

}
